// The payment page
// ================

define(['zepto', 'utils', 'wxshare', 'cityPicker'], function($, utils, wxshare) {
  return {

    init: function(data) {
      
      // forbidden wx share
      wxshare.initShare(data.jsConfig, false)
      
      this.collapseMenu();
      
      this.bindSubmitAction(data.orderId);
      
    },

    collapseMenu: function(){
      
      $(document).on("change", "input[name='my-radio']", function() {
          if($(this).prop("checked")) {
              $(this).parents('li').data("off", "on");
              $(this).parents('li').children('.submenu').addClass('active');
          }else {
              $(this).parents('li').data("off", "off");
              $(this).parents('li').children('.submenu').removeClass('active');
              $($(this).parents('li').find('.submenu textarea')).val('');
          }
      });
      
      $(document).on("change", "input[name='illness']", function(){
          if($(this).prop("checked")) {
              var values=$(this).val();
              if(values =='illnessOn'){
                  $(".descr").addClass('active');
              }
              else{
                  $(".descr").removeClass('active');
                  $(".descr textarea").html("")
              }
          }
      })
      
    },

    // order submit evvent handler
    bindSubmitAction: function(order) {
      
      var thatSubmit = this
      
      var submitButton = $("a.button-submit")
      
      submitButton.on('click', function(e){
        e.preventDefault()
        // init all data
        var data = thatSubmit.onInitData()
        // validate all input
        if(thatSubmit.onValidateData(data)) {
          // do submit order with data
          data = thatSubmit.onAppendData(data)
          thatSubmit.onSubmitOrder(data, order)
        }
      })
      
    },

    // init data
    onInitData: function() {
      return {
        '_method': {
          'value': $('input[name="_method"]').val().trim(),
          'message': '提交方式不能为空'
        },
        'illness': {
            'value': $('input[name="illness"]:checked').val(),
            'message': '个人疾病史请点击确认是或否'
         },
        
      }
    },

    onValidateData: function(data) {
      var that = this;
      var valid = _.find(data, function(item) {
        return !item.value
      })

      if (!!valid) return $.toast(valid.message)
      
      if(!that.validateCheckbox()) {
          return false;
      }
      
      return true
    },
    
    validateCheckbox: function() {
        var result = true;
        $("input[name='my-radio']").each(function(){
            var checked = $(this).prop("checked")
            if(checked) {
              var value =  $($(this).parents('li').find('.submenu textarea')).val();
              var message =$($(this).parents('li').find('.submenu textarea')).data("message");
              if(value == null || value == '') {
                  result = false;
                  return $.toast(message)
              }
            }
        })
        $("input[name='illness']").each(function(){
            var checked = $(this).prop("checked")
            if(checked) {
                if($(this).val() =='illnessOn'){
                    var value =  $($(this).parents('li').next().find('textarea')).val();
                    var message =$($(this).parents('li').next().find('textarea')).data("message");
                    if(value == null || value == '') {
                        result = false;
                        return $.toast(message)
                    } 
                }
             
            }
        })
        
        return result;
    },

    onAppendData: function(data) {
      
      var orderId = $("input[name='orderId']").val();
      if(orderId) {
        data.orderId = {
          'value': orderId
        }
      }
      
//      var diseases = [];
//
//      $('input[name="disease"]:checked').each(function () {
//        diseases.push($(this).val());
//      });
//      
//      var disease = diseases.join()
//      
//      if(disease) {
//        data.disease = {
//          'value': disease
//        }
//      }
//      
      
      var disease = $("textarea[name='disease']").val()
      if(disease) {
        data.disease = {
          'value': disease
        }
      }
      
      
      var sportInjuries = $("textarea[name='sportInjuries']").val();
      if(sportInjuries) {
        data.sportInjuries = {
          'value': sportInjuries
        }
      }
      
      var exerciseHabit = $("textarea[name='exerciseHabit']").val();
      if(exerciseHabit) {
        data.exerciseHabit = {
          'value': exerciseHabit
        }
      }
      
      var pregnant = $("textarea[name='pregnant']").val();
      if(pregnant) {
        data.pregnant = {
          'value': pregnant
        }
      }
      
      var menstruation = $("textarea[name='menstruation']").val();
      if(menstruation) {
        data.menstruation = {
          'value': menstruation
        }
      }
      
      var preparePregnant = $("textarea[name='preparePregnant']").val();
      if(preparePregnant) {
        data.preparePregnant = {
          'value': preparePregnant
        }
      }
      

      var stomach = $("textarea[name='stomach']").val();
      if(stomach) {
        data.stomach = {
          'value': stomach
        }
      }
      

      var gluttony = $("textarea[name='gluttony']").val();
      if(gluttony) {
        data.gluttony = {
          'value': gluttony
        }
      }
      

      var foodPreference = $("textarea[name='foodPreference']").val();
      if(foodPreference) {
        data.foodPreference = {
          'value': foodPreference
        }
      }
      

      var workArrangements = $("textarea[name='workArrangements']").val();
      console.log(workArrangements)
      if(workArrangements) {
        data.workArrangements = {
          'value': workArrangements
        }
      }
      
      var remarks = $("textarea[name='remarks']").val();
      console.log(remarks)
      if(remarks) {
        data.remarks = {
          'value': remarks
        }
      }
      
      return data;
    },

    onSubmitOrder: function(data, order) {
      
      console.log($("textarea[name='remarks']").val())

      $.showPreloader('正在提交')

      var processedData = _.mapObject(data, function(obj) {
        return obj.value
      })
      $.ajax({
        type: 'POST',
        url: __CTX__.root + '/orders/' + order + '/investigations/health',
        data: processedData
      }).done(function(response) {
        $.hidePreloader()
        utils.processResult(response, function(result) {
          $.toast('填写健康数据成功')
          setTimeout(function() {
            window.location.href = __CTX__.root + '/orders/' +order+ "/investigations";
          }, 1000)
        }, function(result) {
          $.toast(result.message || '填写健康数据失败')
        })
      })
      
    }
  }
})
